<template>
  <div class="addModal">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="名称模版" prop="transName">
        <el-input v-model="ruleForm.transName"></el-input>
      </el-form-item>
      <el-form-item label="模板类型" prop="isFreeFee">
        <el-radio v-model="ruleForm.isFreeFee" :label="0"
          >买家承担运费</el-radio
        >
        <el-radio
          @change="FunisFreeFee()"
          v-model="ruleForm.isFreeFee"
          :label="1"
          >卖家包邮</el-radio
        >
      </el-form-item>
      <el-form-item label="收费方式" prop="chargeType">
        <el-radio
          :disabled="ruleForm.isFreeFee == 1"
          v-model="ruleForm.chargeType"
          :label="0"
          >按件数</el-radio
        >
        <el-radio
          :disabled="ruleForm.isFreeFee == 1"
          v-model="ruleForm.chargeType"
          :label="1"
          >按重量</el-radio
        >
        <el-radio
          :disabled="ruleForm.isFreeFee == 1"
          v-model="ruleForm.chargeType"
          :label="2"
          >按体积</el-radio
        >
      </el-form-item>

      <!-- 表格 -->
      <el-table border :data="ruleForm.transfees" stripe style="width: 100%">
        <el-table-column
          align="center"
          prop="date"
          label="可配送区域"
          width="250"
        >
          <template #default="{ row, $index }">
            <div v-if="$index === 0">所有地区</div>
            <div v-else>
              <div
                v-for="(item, index) in ruleForm.transfees[$index].cityList"
                :key="index"
              >
                <el-tag v-if="item.areaName" size="mini">
                  {{ item.areaName }}</el-tag
                >
              </div>

              <!-- 非第一项的显示内容，这里可以根据 row 数据动态显示 -->
              请选择可配送区域
              <span class="blue" @click="FunTree($index, 1)">编辑</span
              ><span @click="FunDel($index)" class="blue">删除</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="firstPiece" label="首件">
          <template v-slot="{ row }">
            <el-form-item prop="firstPiece">
              <el-input-number
                :disabled="ruleForm.isFreeFee == 1"
                style="width: 90%; margin: auto"
                v-model="row.firstPiece"
                :min="0"
                :step="1"
                controls-position="right"
              >
              </el-input-number>
            </el-form-item>
            <!-- {{ row }} -->
          </template>
        </el-table-column>
        <el-table-column align="center" label="运费">
          <template v-slot="{ row, $index }">
            <el-form-item prop="firstFee">
              <el-input-number
                :disabled="ruleForm.isFreeFee == 1"
                style="width: 90%; margin: auto"
                v-model="ruleForm.transfees[$index].firstFee"
                :min="0"
                :step="1"
                controls-position="right"
              >
              </el-input-number>
            </el-form-item>
            <!-- {{ row }} -->
          </template>
        </el-table-column>
        <el-table-column align="center" prop="continuousPiece" label="续件">
          <template v-slot="{ row }">
            <el-form-item class="bb" prop="continuousPiece">
              <el-input-number
                :disabled="ruleForm.isFreeFee == 1"
                style="width: 90%; margin: auto"
                v-model="row.continuousPiece"
                :min="0"
                :step="1"
                controls-position="right"
              >
              </el-input-number>
            </el-form-item>
            <!-- {{ ruleForm.transfees[0].continuousPiece }} -->
            <!-- {{ row }} -->
          </template>
        </el-table-column>
        <el-table-column align="center" prop="continuousFee" label="续费">
          <template v-slot="{ row }">
            <el-form-item class="bb" prop="continuousFee">
              <!-- <el-input class="bb" v-model="row.continuousFee"></el-input> -->
              <el-input-number
                :disabled="ruleForm.isFreeFee == 1"
                class="bb"
                style="width: 90%; margin: auto"
                v-model="row.continuousFee"
                :min="0"
                :step="1"
                controls-position="right"
              >
              </el-input-number>
            </el-form-item>
            <!-- {{ row }} -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 表格 -->
      <el-button
        v-if="ruleForm.isFreeFee == 0"
        @click="FunTable1"
        style="margin: 10px 0 10px 10px"
        type="primary"
        ><i class="el-icon-location-outline"></i
        >点击添加可配送的区域和运营</el-button
      >
      <div v-if="ruleForm.isFreeFee == 0">
        <el-checkbox v-model="checked">指定条件包邮</el-checkbox>
      </div>
      <!-- 表格2 -->
      <el-table
        v-if="ruleForm.isFreeFee == 0"
        v-show="checked"
        border
        :data="ruleForm.transfeeFrees"
        stripe
        style="width: 100%; margin: 20px 0"
      >
        <el-table-column
          align="center"
          prop="date"
          label="可配送区域"
          width="250"
        >
          <template #default="{ row, $index }">
            <div
              v-for="(item, index) in ruleForm.transfeeFrees[$index]
                .freeCityList"
              :key="index"
            >
              <el-tag v-if="item.areaName" size="mini">
                {{ item.areaName }}</el-tag
              >
            </div>

            <!-- {{[0].level }}11 -->
            <!-- {{ $index }} -->

            <!-- 非第一项的显示内容，这里可以根据 row 数据动态显示 -->
            请选择指定包邮城市
            <span class="blue" @click="FunTree($index, 2)">编辑</span
            ><span @click="FunDel2($index)" class="blue">删除</span>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="freeType" label="设置包邮条件">
          <template v-slot="{ row }">
            <el-radio @change="FunTabfree2" v-model="row.freeType" :label="0"
              >满件/重量/体积包邮</el-radio
            >
            <el-radio @change="FunTabfree2" v-model="row.freeType" :label="1"
              >满金额包邮</el-radio
            >
            <el-radio @change="FunTabfree2" v-model="row.freeType" :label="2"
              >满件/重量/体积包邮且满金额包邮</el-radio
            >
            <!-- {{ row }} -->
          </template>
        </el-table-column>
        <el-table-column align="left" prop="amount" label="件数">
          <template v-slot="{ row }">
            <div v-if="row.freeType == 0" style="margin-bottom: 20px">
              满
              <el-input style="width: 100px" v-model="row.amount"></el-input
              >元包邮
            </div>
            <div v-if="row.freeType == 1" style="margin-bottom: 20px">
              满
              <el-input style="width: 100px" v-model="row.piece"></el-input
              >件/重量/体积包邮
            </div>
            <div v-if="row.freeType == 2">
              满
              <el-input style="width: 100px" v-model="row.amount"></el-input
              >元包邮
              <p>
                满
                <el-input style="width: 100px" v-model="row.piece"></el-input
                >件/重量/体积包邮
              </p>
            </div>

            <!-- {{ row }} -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格2 -->
      <div>
        <el-button
          :disabled="!checked"
          v-if="ruleForm.isFreeFee == 0"
          @click="FunTable2"
          style="margin: 10px 0 10px 10px"
          type="primary"
          ><i class="el-icon-location-outline"></i
          >点击添加指定包邮条件</el-button
        >
      </div>
      <el-form-item style="text-align: right">
        <el-button
          :disabled="disabled"
          type="primary"
          @click="submitForm('ruleForm')"
          >立即创建</el-button
        >
        <el-button @click="resetForm()">取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(245, 247, 250,0.5)"
      append-to-body
      title="选择配送区域"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <div>
        <el-tree
          ref="tree"
          :data="treeData"
          show-checkbox
          :props="defaultProps"
          @check-change="handleCheckChange"
        ></el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="madelTree">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import Token from '@/api/headers'
// import { openRules } from './config'
export default {
  props: {
    currentRow: '' //不严谨

    // 严谨
    //  currentRow: {
    //   type: String,
    //   default: "",
    // },
  },
  data() {
    return {
      // openRules, //引入规则
      disabled: false,
      dialogVisible: false,
      checked: false,
      // ifTab2:true

      ids: '',
      ruleForm: {
        transName: null, //模版名称
        isFreeFee: 0, //模板类型
        chargeType: 0, //收费方式
        hasFreeCondition: 0,
        t: Date.now(),
        transfees: [
          {
            cityList: [], //城市
            status: 1, //默认
            firstPiece: 1, //首件
            firstFee: 1, //运费
            continuousPiece: 1, //续件
            continuousFee: 1 //续费
          }
        ], //可配送区域
        transfeeFrees: [
          {
            freeType: 0, //设置包邮条件 0 1 2
            freeCityList: [], //城市
            amount: '', //满多少包邮
            piece: '' //满多少件重量体积包
          }
        ] //指定条件包邮
      },
      rules: {
        transName: [
          { required: true, message: '请输入模版名称', trigger: 'blur' }
        ]
        // isFreeFee: [
        //   { required: true, message: '请输入模版类型', trigger: 'submit' }
        // ],
        // firstPiece: [
        //   { required: true, message: '内容不能为空', trigger: 'submit' }
        // ],
        // firstFee: [
        //   { required: true, message: '内容不能为空', trigger: 'submit' }
        // ],
        // continuousPiece: [
        //   { required: true, message: '内容不能为空', trigger: 'blur' }
        // ],
        // continuousFee: [
        //   { required: true, message: '内容不能为空', trigger: 'blur' }
        // ]
      },
      loading: false, //加载
      // tree
      flatData: [], // 存储后端返回的扁平数据
      treeData: [], // 存储转换后的树形结构数据
      defaultProps: {
        children: 'children',
        label: 'areaName'
      },
      indexx: '', //编辑id
      cityList: [], //存储城市
      isof: '' //区分tab
      // tree
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm)

          axios
            .post(
              'http://47.104.167.34:9305/apis/shop/transport',
              this.ruleForm,
              Token
            )
            .then((response) => {
              console.log(response)
              this.$message({
                message: '恭喜你，添加成功',
                type: 'success'
              })
              this.$emit('modalSaveEmit')
            })
            .catch((error) => {
              this.$message.error('添加失败！')
            })
        } else {
          console.log('error submit!!')
          // this.disabled = false
          return false
        }
      })
    },
    resetForm() {
      // this.$refs[formName].resetFields()
      this.$emit('modalCancelEmit')
    },
    // 模版类型切换
    FunisFreeFee() {
      console.log(this.ruleForm.chargeType)

      this.ruleForm.chargeType = 0
      this.ruleForm.transfees = [
        {
          cityList: [], //城市
          status: 1, //默认
          firstPiece: 1, //首件
          firstFee: 0, //运费
          continuousPiece: 1, //续件
          continuousFee: 0 //续费
        }
      ]
    },
    //表格一
    FunTable1() {
      this.ruleForm.transfees.push({
        cityList: [
          {
            areaId: '',
            areaName: '',
            areas: '',
            level: '',
            parentId: '',
            _level: ''
          }
        ], //城市
        status: '', //默认
        firstPiece: '', //首件
        firstFee: '', //运费
        continuousPiece: '', //续件
        continuousFee: '' //续费
      })
    },
    //表格2
    FunTable2() {
      // this.cityList = []
      this.ruleForm.transfeeFrees.push({
        freeType: 0, //设置包邮条件 0 1 2
        freeCityList: [
          {
            areaId: '',
            areaName: '',
            areas: '',
            level: '',
            parentId: '',
            _level: ''
          }
        ], //城市
        amount: '', //满多少包邮
        piece: '' //满多少件重量体积包
      })
    },
    // 表格删除1
    FunDel(i) {
      console.log(i)
      this.ruleForm.transfees.splice(i, 1)
    },
    // 表格删除2
    FunDel2(i) {
      console.log(i)
      this.ruleForm.transfeeFrees.splice(i, 1)
    },
    FunTabfree2(e) {
      console.log(e)
      if (e == 2) {
      }
    },
    // tree
    FunTree(i, d) {
      // this.cityList = []
      this.loading = true
      this.dialogVisible = true
      this.indexx = i
      this.isof = d
      // 调用接口
      this.ruleForm
      axios
        .get('http://47.104.167.34:9305/apis/admin/area/list', {
          ...Token
        })
        .then((response) => {
          console.log(response.data.data)
          console.log(1)
          const mockData = response.data.data
          this.flatData = mockData
          this.treeData = this.convertToTree(this.flatData)
          // this.GetList()
        })
        .catch((error) => {
          console.log(error)
        })
        .finally(() => {
          this.loading = false
        })
    },
    // tree
    // 转换
    convertToTree(data) {
      const map = {}
      const tree = []
      data.forEach((item) => {
        map[item.areaId] = { ...item, children: [] }
      })
      data.forEach((item) => {
        const parent = map[item.parentId]
        if (parent) {
          parent.children.push(map[item.areaId])
        } else {
          tree.push(map[item.areaId])
        }
      })
      return tree
    },
    //选择
    handleCheckChange(data, checked, indeterminate) {
      console.log(data)

      this.cityList = []
      const selectedNodes = this.$refs.tree.getCheckedNodes()
      selectedNodes.forEach((node) => {
        this.cityList.push({
          areaId: node.areaId,
          areaName: node.areaName,
          parentId: node.parentId,
          level: node.level,
          areas: node.areas,
          _level: node.level
        })
      })
      console.log('转换后的数据数组 cityList：', this.cityList)
    },
    //模态框确定
    madelTree() {
      this.dialogVisible = false
      if (this.isof == 1) {
        console.log(1)
        console.log(this.indexx, '////')

        // this.ruleForm.transfees[this.indexx].cityList = []
        this.$set(
          this.ruleForm.transfees[this.indexx],
          'cityList',
          this.cityList
        )
        console.log(this.ruleForm.transfees[this.indexx].cityList)
      } else {
        console.log(2)
        console.log(this.indexx, '////')
        this.ruleForm.transfeeFrees[this.indexx].freeCityList = []
        this.$set(
          this.ruleForm.transfeeFrees[this.indexx],
          'freeCityList',
          this.cityList
        )
        console.log(this.ruleForm.transfeeFrees[this.indexx].freeCityList)
      }
      console.log(this.ruleForm)
    }
  }
}
</script>

<style lang="scss" scoped>
.addModal::v-deep {
  .el-table .el-form-item__content {
    margin-left: 0rem !important;
  }
  .blue {
    color: #1890ff;
    margin: 0px 5px;
    cursor: pointer;
  }
}
</style>